<template>
	<!-- 收货地址页 -->
	<view class="address">
		<!-- 用户收货地址列表 -->
		<view class="addressList">
			<u-address :canSelect="needSelectAddr" :userAddressList="addressList" :defaultAddress="defaultAddress"
				@delete="deleteAddress" @select="selectedAddr"></u-address>
		</view>

		<!-- 按钮 -->
		<view class="address-button">
			<u-button v-if="needSelectAddr" text="确定" color="#3c9cff" shape="circle" @click="confirmAddr"
				:customStyle="{marginBottom: '20rpx'}"></u-button>
			<u-button text="+新增地址" color="#ff516b" shape="circle" @click="toAddAddress"></u-button>
		</view>
	</view>
</template>

<script>
	import uAddress from '@/pages_mine/components/u-address/u-address.vue';
	export default {
		components: {
			'u-address': uAddress,
		},
		data() {
			return {
				// 是否增加选择地址功能
				needSelectAddr: false,
				// 用户地址信息（除默认地址）
				addressList: [],
				// 用户默认地址
				defaultAddress: {},
				// 选中地址的id
				selectedId: null,
			}
		},
		methods: {
			// 获取用户收货地址信息
			async getUserAddress(hideLoading = false) {
				// 获取用户所有收货地址
				let all = await this.$api.address.getAddressAPI(hideLoading);
				let allAddr = all.result;
				// 收货地址为空
				if (!allAddr.length) {
					this.addressList = [];
					this.defaultAddress = {};
					return;
				}
				// 获取用户默认收货地址
				let def = await this.$api.address.getDefaultAddressAPI(hideLoading);
				let defAddr = def.result;
				// 保存地址信息
				// console.log(allAddr);
				// console.log(defAddr);
				this.addressList = allAddr.filter(a => a.id !== defAddr.id);
				this.defaultAddress = defAddr;
				// 默认选中默认收货地址
				this.selectedId = this.defaultAddress.id;
			},
			// 接收子组件通知，删除收货地址
			deleteAddress(id) {
				uni.showModal({
					content: '是否删除该地址',
					success: async (res) => {
						if (res.confirm) {
							let data = await this.$api.address.deleteAddressAPI(id);
							// 重新获取地址
							this.getUserAddress(true);
						}
					}
				})
			},
			// 接收子组件通知，选择收货地址
			selectedAddr(id) {
				this.selectedId = id;
			},
			// 跳转到新增地址页
			toAddAddress() {
				this.$Router.push('/update_address');
			},
			// 确认选择地址
			confirmAddr() {
				// 携带地址id返回下单页
				// 保存选中地址的id
				uni.setStorageSync('addrId', this.selectedId);
				// 返回上一页
				this.$Router.back();
			}
		},
		onShow() {
			// 获取用户收货地址信息
			this.getUserAddress();
			// 判断是否需要选择地址功能
			this.needSelectAddr = this.$Route.query.needSelect || false;
		}
	}
</script>

<style lang="scss" scoped>
	.address {
		@include page-bgc(#e9ecf0);
		padding-bottom: 300rpx;

		// 用户收货地址列表
		.addressList {}

		// 新增按钮
		.address-button {
			position: fixed;
			bottom: 80rpx;
			left: 0;
			z-index: 999;
			width: 100%;
			padding: 0 20rpx;
			box-sizing: border-box;
		}
	}
</style>